// pages/edit/edit.js
import lotteryService from '../../services/lottery';
import config from '../../config/api';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    conditionType: 0,
    dates: [],
    hours: [
      '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23
    ],
    minutes: ["00", "30"],
    isShowPicker: false,
    currentAwardType: 0,
    imgPath: "../img/bg.png",
    vip: app.globalData.vip, // 是否是vip用户,
    date: "",
    hour: '00',
    minute: '00'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const lotteryId = options.lottery_id;
    lotteryService.detail(lotteryId)
      .then(res => {
        debugger;
        if (res.resCode == config.Lottery.ResCode.Success) {
          const lottery = res.data;
          this.setData({
            conditionType: lottery.method,
            imgPath: lottery.image,
            currentAwardType: lottery.items[0].type,
          });
          if (config.Lottery.Type.Object ==lottery.items[0].type){
            this.setData({
              awardNameValue: lottery.items[0].name,
              awardNumberValue: lottery.items[0].count,
            });
          }else{
            this.setData({
              moneyCountValue: lottery.items[0].packet,
              awardNumberValue: lottery.items[0].count
            });            
          }
        }
      })
      .catch(err => console.error(err));
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    debugger;
    let now = new Date();
    let dates = [];
    this.setData({
      hour: now.getHours() < 10 ? '0' + now.getHours() : now.getHours(),
      minute: now.getMinutes() < 30 ? 30 : '00'
    })
    for (let i = 0; i < 7; i++) {
      let targetMS = now.getTime() + 1000 * 60 * 60 * 24 * i;
      let targetDate = new Date(targetMS);
      let year = targetDate.getFullYear();
      let month = targetDate.getMonth() + 1;
      if (month < 10) {
        month = "0" + month;
      }
      let date = targetDate.getDate();
      if (date < 10) {
        date = "0" + date;
      }
      let str = [year, month, date].join("-");
      if (i == 0) {
        this.setData({
          date: str
        });
      }
      dates.push(str);
    }
    this.setData({
      dates: dates
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
  * 编辑开奖条件
  */
  editCondition: function () {
    //0：按时间自动开奖 1：按人数自动开奖 2：手动开奖
    const that = this;
    wx.showActionSheet({
      itemList: ['按时间自动开奖', '按人数自动开奖', '手动开奖', "当面开奖"],
      success: function (res) {
        that.setData({
          conditionType: res.tapIndex,
        })
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },
  /**
   * 购买 vip
   */
  buyVip: function () {
    lotteryService.buyVip().then(res => {
      console.log(res)
      if (res) {
        wx.requestPayment(
          {
            'timeStamp': res.data.timeStamp,
            'nonceStr': res.data.nonceStr,
            'package': res.data.package,
            'signType': 'MD5',
            'paySign': res.data.paySign,
            'success': function (success) {
              console.log(success)
            },
            'fail': function (fail) {
              console.log(fail)
            },
            'complete': function (complete) {
              console.log(complete)
            }
          })
      }
    })
      .catch(err => {
        // 发起失败
        console.error(err);
      });
  },
  /**
   * 展示时间选择器
   */
  triggerPickerShow: function () {
    debugger
    this.setData({
      isShowPicker: !this.data.isShowPicker
    });
  },
  /**
   * 时间选择器触发事件
   */
  pickerChange: function (e) {
    const val = e.detail.value
    this.setData({
      date: this.data.dates[val[0]],
      hour: this.data.hours[val[1]],
      minute: this.data.minutes[val[2]]
    });
  },
  /**
   * 修改背景图片
   */
  changeImg: function () {
    debugger;
    const that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths[0];
        const ext = tempFilePaths.substr(tempFilePaths.lastIndexOf(".") + 1);
        if (config.Lottery.AllowImgType.indexOf(ext) == -1) {
          wx.showModal({
            title: '警告',
            content: '图片格式只支持png,jpg,jpeg',
            success: function (res) {
            }
          })
          return;
        }
        lotteryService.upload(tempFilePaths)
          .then(res => {
            debugger;
            if (res.resCode == config.Lottery.ResCode.Success) {
            }
          })
          .catch(err => {
            // 发起失败
            console.error(err);
          });
        that.setData({
          imgPath: tempFilePaths
        });
      }
    })
  },
  /**
   * 发起抽奖
   */
  launchLottery: function (e) {
    debugger;
    const image = this.data.imgPath == '../img/bg.png' ? '../../pages/img/bg.png' : this.data.imgPath;
    let params = {
      method: this.data.conditionType,
      items: [],
      image: image
    };
    if (config.Lottery.Method.Auto == this.data.conditionType) {
      let time = this.data.date + " " + [this.data.hour, this.data.minute, "00"].join(":");
      params.drawnDatetime = time;
    } else if (config.Lottery.Method.JoinedCount == this.data.conditionType) {
      params.drawnCount = Number(e.detail.value.lotteryNum);
    }
    params.items = [];
    let item = {
      type: this.data.currentAwardType,
      level: 1
    }
    if (this.data.currentAwardType == config.Lottery.Type.Object) {
      item.count = Number(e.detail.value.awardNumber);
      item.name = e.detail.value.awardName;
    } else {
      item.count = Number(e.detail.value.moneyCount);
      item.packet = e.detail.value.money;
    }
    params.items.push(item);
    lotteryService.launch(params)
      .then(res => {
        if (res.resCode == config.Lottery.ResCode.Success) {
          wx.navigateTo({
            url: '../addSuccess/addSuccess?lotteryId=' + res.data.lotteryId,
          })
        }
      })
      .catch(err => {
        // 发起失败
        console.error(err);
      });
  }
})